﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using MongoDB.Driver;
using Demo.AttachFileService.Mongo.Domain.Entities;

namespace Demo.AttachFileService.Mongo {
    //public partial class IMongoEntity {
    //    /// <summary>
    //    /// 基础ID
    //    /// </summary>
    //    public ObjectId _id { get; set; }
    //}
    //public class MongoContext {
    //    public MongoContext() {
    //        Client = new MongoClient(ABCDEFG.GetAppSetting("mongodb"));
    //    }

    //    public MongoContext(string connectionName) {
    //        Client = new MongoClient(MengTConfig.GetAppSetting(connectionName));
    //    }

    //    private MongoClient Client { get; set; }

    //    private IMongoDatabase DataBase { get => Client.GetDatabase("MengTLog"); }

    //    public IMongoCollection<T> DbSet<T>() where T : IMongoEntity => DataBase.GetCollection<T>("MengTLog.Logger");

    //}

    public static class MongoDbExtensions {
        public static void Insert<T>(this IMongoCollection<T> collenction, T Model) where T : IEntity<string>
                  => collenction.InsertOne(Model);

        public static void Inserts<T>(this IMongoCollection<T> collenction, IEnumerable<T> Model) where T : IEntity<string>
                 => collenction.InsertMany(Model);

        /// <summary>
        /// 查找第一个
        /// </summary>
        public static T FirstOrDefault<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IEntity<string> {
            if (expression == null) throw new ArgumentNullException(nameof(expression));
            return collenction.Find(expression).FirstOrDefault();
        }

        /// <summary>
        /// 查找符合数据列表
        /// </summary>
        public static List<T> FindToList<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IEntity<string> {
            if (expression == null) throw new ArgumentNullException(nameof(expression));
            return collenction.Find(expression).ToList();
        }

        /// <summary>
        /// 删除全部匹配数据
        /// </summary>
        public static void Delete<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IEntity<string> {
            if (expression == null) throw new ArgumentNullException(nameof(expression));
            collenction.DeleteManyAsync(expression);
        }


        /// <summary>
        /// 删除一个
        /// </summary>
        public static void DeleteOne<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IEntity<string> {
            if (expression == null) throw new ArgumentNullException(nameof(expression)); 
            collenction.DeleteOneAsync(expression);
        }
    }
}